<template>
  <div class="mod-config">
    <el-form
      :inline="true"
      :model="dataForm"
      @keyup.enter.native="getDataList()"
    >
      <!-- <el-form-item>
        <el-select
          clearable
          v-model="dataForm.projectId"
          placeholder="所属项目"
        >
          <el-option
            v-for="item in projectList"
            :key="item.id"
            :label="item.projectName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-date-picker
          v-model="dateRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          :default-time="['00:00:00', '23:59:59']"
          align="right"
          @change="timeChange"
          clearable
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
        <!-- <el-button
          type="danger"
          v-if="isAuth('generator:bcarledger:delete')"
          @click="deleteHandle()"
          :disabled="dataListSelections.length <= 0"
          >批量删除</el-button
        > -->
        <el-button
          v-if="isAuth('generator:bcarledger:handleExport')"
          @click="handleExport()"
          >导出</el-button
        >
        <el-button v-print="'#printTest'">打印</el-button>
      </el-form-item>
    </el-form>
    <el-table
      id="printTest"
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%"
    >
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50"
      >
      </el-table-column>
      <el-table-column
        label="序号"
        type="index"
        header-align="center"
        align="center"
        width="50"
      >
      </el-table-column>
      <el-table-column
        prop="projectName"
        header-align="center"
        align="center"
        label="所属项目"
      >
      </el-table-column>
      <el-table-column
        prop="carNum"
        header-align="center"
        align="center"
        label="总车辆数"
      >
        <template slot-scope="scope">
          <div
            :class="scope.row.carNum === 0 ? 'nomrol' : 'drilling'"
            @click="drilling(1, scope.row)"
          >
            {{ scope.row.carNum }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="sum"
        header-align="center"
        align="center"
        label="总车次"
      >
        <template slot-scope="scope">
          <div
            :class="scope.row.sum === 0 ? 'nomrol' : 'drilling'"
            @click="drilling(2, scope.row)"
          >
            {{ scope.row.sum }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="normal"
        header-align="center"
        align="center"
        label="正常车次"
      >
        <template slot-scope="scope">
          <div
            :class="scope.row.normal === 0 ? 'nomrol' : 'drilling'"
            @click="drilling(3, scope.row)"
          >
            {{ scope.row.normal }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="abnormal"
        header-align="center"
        align="center"
        label="异常车次"
      >
        <template slot-scope="scope">
          <div
            :class="scope.row.abnormal === 0 ? 'nomrol' : 'drilling'"
            @click="drilling(4, scope.row)"
          >
            {{ scope.row.abnormal }}
          </div>
        </template>
      </el-table-column>
      <!-- <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="deleteHandle(scope.row.id)"
            >删除</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="checkDetailed(scope.row.id)"
            >查看明细</el-button
          >
        </template>
      </el-table-column> -->
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageParams.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageParams.limit"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination>
    <el-dialog title="总车次" :visible.sync="dialogTableVisible">
      <el-date-picker
        v-model="dateRangeAll"
        type="datetimerange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="yyyy-MM-dd HH:mm:ss"
        align="right"
        @change="timeChangeitem"
        clearable
      >
      </el-date-picker>
      <el-button @click="handleExport2()">导出</el-button>
      <el-table
        style="margin-top: 20px"
        :data="gridData"
        @selection-change="selectionChangeHandle2"
      >
        <el-table-column
          type="selection"
          header-align="center"
          align="center"
          width="50"
        ></el-table-column>
        <el-table-column property="carCode" label="车牌"></el-table-column>
        <el-table-column property="sum" label="总车次"></el-table-column>
        <el-table-column property="normal" label="正常"></el-table-column>
        <el-table-column property="abnormal" label="异常"></el-table-column>
      </el-table>
      <el-pagination
        @size-change="sizeChangeHandle2"
        @current-change="currentChangeHandle2"
        :current-page="pageParams2.page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageParams2.limit"
        :total="totalPage2"
        layout="total, sizes, prev, pager, next, jumper"
      >
      </el-pagination>
    </el-dialog>

    <!-- 弹窗, 新增 / 修改 -->
    <leader-track v-if="trackVisible" ref="leaderTrack"></leader-track>
    <leader-info v-if="infoVisible" ref="leaderInfo"></leader-info>
  </div>
</template>

<script>
import leaderTrack from "./leaderTrack.vue";
import leaderInfo from "./leaderInfo.vue";
export default {
  data() {
    return {
      print: {
        id: "printArea",
        popTitle: "打印", // 打印配置页上方标题
        extraHead: "", //最上方的头部文字，附加在head标签上的额外标签,使用逗号分隔
        preview: "", // 是否启动预览模式，默认是false（开启预览模式，可以先预览后打印）
        previewTitle: "", // 打印预览的标题（开启预览模式后出现）,
        previewPrintBtnLabel: "", // 打印预览的标题的下方按钮文本，点击可进入打印（开启预览模式后出现）
        zIndex: "", // 预览的窗口的z-index，默认是 20002（此值要高一些，这涉及到预览模式是否显示在最上面）
        previewBeforeOpenCallback() {}, //预览窗口打开之前的callback（开启预览模式调用）
        previewOpenCallback() {}, // 预览窗口打开之后的callback（开启预览模式调用）
        beforeEntryIframe() {
          const cells = document.querySelectorAll(".cell");
          [].slice.call(cells).forEach(item => {
            // 为了让表格中的内容自动换行，不需要的话可以删掉
            item.style.whiteSpace = "pre-wrap";
          });
        },
        openCallback() {}, // 调用打印之后的回调事件
        closeCallback() {}, //关闭打印的回调事件（无法确定点击的是确认还是取消）
        url: "",
        standard: "",
        extraCss: ""
      },

      dialogTableVisible: false,
      gridData: [],
      projectList: [],
      dataForm: {
        // projectId: "",
        endDate: new Date(parseInt(+new Date()))
          .toLocaleString()
          .replace(/[/]+/g, "-"),
        startDate: new Date(parseInt(+new Date() - 3600 * 1000 * 24))
          .toLocaleString()
          .replace(/[/]+/g, "-")
      },
      dataList: [],
      pageParams: {
        page: 1,
        limit: 10
      },
      pageParams2: {
        page: 1,
        limit: 10,
        projectId: "",
        endDate: new Date(parseInt(+new Date()))
          .toLocaleString()
          .replace(/[/]+/g, "-"),
        startDate: new Date(parseInt(+new Date() - 3600 * 1000 * 24))
          .toLocaleString()
          .replace(/[/]+/g, "-")
      },
      totalPage: 0,
      totalPage2: 0,
      dataListLoading: false,
      dataListSelections: [],
      dataListSelections2: [],
      addOrUpdateVisible: false,
      trackVisible: false,
      infoVisible: false,
      statusList: [
        {
          label: "异常",
          value: 0
        },
        {
          label: "合格",
          value: 1
        }
      ],

      dateRange: [
        new Date(parseInt(+new Date() - 3600 * 1000 * 24))
          .toLocaleString()
          .replace(/[/]+/g, "-"),
        new Date(parseInt(+new Date())).toLocaleString().replace(/[/]+/g, "-")
      ],
      dateRangeAll: [
        new Date(parseInt(+new Date() - 3600 * 1000 * 24))
          .toLocaleString()
          .replace(/[/]+/g, "-")
        //new Date(parseInt(+new Date())).toLocaleString().replace(/[/]+/g, "-")
      ]
    };
  },
  components: { leaderTrack, leaderInfo },
  activated() {
    this.getDataList();
  },
  mounted() {
    this.getProject();
  },

  methods: {
    // 进入弹框
    getall(projectId) {
      this.dialogTableVisible = true;
      //  console.log(projectId,'projectId')
      //   setTimeout(()=>{

      //   },1000
      //   )
      this.pageParams2.projectId = projectId;
      this.getcarList();
    },
    timeChange(e) {
      if (e) {
        this.dataForm.startDate = e[0];
        this.dataForm.endDate = e[1];
      } else {
        this.dataForm.startDate = null;
        this.dataForm.endDate = null;
      }
    },
    timeChangeitem(e) {
      if (e) {
        this.pageParams2.startDate = e[0];
        this.pageParams2.endDate = e[1];
      } else {
        this.pageParams2.startDate = null;
        this.pageParams2.endDate = null;
      }
      this.getcarList();
    },
    // 处理数组
    getArr(e) {
      return e.split(",");
    },

    // 查看异常
    infoHandle(id) {
      this.infoVisible = true;
      this.$nextTick(() => {
        this.$refs.leaderInfo.init(id);
      });
    },
    // 导出
    handleExport() {
      console.log("222");
      let ids;
      if (this.dataListSelections.length === 0) {
        ids = this.dataList.map(item => {
          return item.id;
        });
      } else {
        ids = this.dataListSelections.map(item => {
          return item.id;
        });
      }
      if (ids.length > 0) {
        this.$http({
          url: this.$http.adornUrl(`/sys/car/report/handleExport/?ids=${ids}`),
          method: "post",
          responseType: "blob"
        }).then(({ data }) => {
          console.log(data, "data");
          const blob = new Blob([data], { type: "application/vnd.ms-excel" });
          let a = document.createElement("a");
          a.download = "运输报表.xlsx";
          a.href = URL.createObjectURL(blob);
          document.getElementsByTagName("body")[0].appendChild(a);
          a.click();
          a.parentNode.removeChild(a);
        });
      }
    },
    // 导出弹框内容
    handleExport2() {
      let ids;
      if (this.dataListSelections2.length === 0) {
        ids = this.gridData.map(item => {
          return item.id;
        });
      } else {
        ids = this.dataListSelections2.map(item => {
          return item.id;
        });
      }
      if (ids.length > 0) {
        this.$http({
          url: this.$http.adornUrl(`/sys/car/report/handleExport?ids=${ids}`),
          method: "get",
          responseType: "blob"
        }).then(({ data }) => {
          console.log(data, "data");
          const blob = new Blob([data], { type: "application/vnd.ms-excel" });
          let a = document.createElement("a");
          a.download = "车次报表.xlsx";
          a.href = URL.createObjectURL(blob);
          document.getElementsByTagName("body")[0].appendChild(a);
          a.click();
          a.parentNode.removeChild(a);
        });
      }
    },
    // 获取所属项目
    getProject() {
      this.$http({
        url: this.$http.adornUrl(`/sys/project/management/list`),
        method: "get"
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.projectList = data.list;
        }
      });
    },
    // 获取数据列表
    getDataList(flag) {
      if (flag) {
        this.pageParams.page = 1;
      }
      if (
        JSON.parse(sessionStorage.getItem("permissions")).indexOf("selectAll") >
        -1
      ) {
        this.dataForm.selectAll = 1;
      } else if (
        JSON.parse(sessionStorage.getItem("permissions")).indexOf(
          "selectAll"
        ) === -1
      ) {
        this.dataForm.selectAll = 0;
      }
      this.dataListLoading = true;
      let params = { ...this.pageParams, ...this.dataForm };
      this.$http({
        url: this.$http.adornUrl("/sys/car/report/page"),
        // url: this.$http.adornUrl("/sys/car/report/car/page"),
        method: "get",
        params: this.$http.adornParams(params)
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list;
          this.totalPage = data.page.totalCount;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
    },
    // 根据车次进行统计
    getcarList() {
      let params = { ...this.pageParams2 };
      this.$http({
        url: this.$http.adornUrl("/sys/car/report/car/page"),
        method: "get",
        params: this.$http.adornParams(params)
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.gridData = data.page.list;
          this.totalPage2 = data.page.totalCount;
        } else {
          this.gridData = [];
          this.totalPage2 = 0;
        }
      });
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageParams.limit = val;
      this.pageParams.page = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageParams.page = val;
      this.getDataList();
    },
    // 每页数
    sizeChangeHandle2(val) {
      this.pageParams2.limit = val;
      this.pageParams2.page = 1;
      this.getcarList();
    },
    // 当前页
    currentChangeHandle2(val) {
      this.pageParams2.page = val;
      this.getcarList();
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val;
    },
    selectionChangeHandle2(val) {
      this.dataListSelections2 = val;
    },
    // 删除
    deleteHandle(id) {
      var ids = id
        ? [id]
        : this.dataListSelections.map(item => {
            return item.id;
          });
      this.$confirm(
        `确定对[id=${ids.join(",")}]进行[${id ? "删除" : "批量删除"}]操作?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        this.$http({
          url: this.$http.adornUrl("/sys/car/report/delete"),
          method: "delete",
          data: this.$http.adornData(ids, false)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.getDataList();
              }
            });
          } else {
            this.$message.error(data.msg);
          }
        });
      });
    },

    //查看明细
    checkDetailed(id) {
      this.$router.push({
        path: "management-ledgerManagement",
        query: {
          reportId: id
        }
      });
    },

    //钻取
    drilling(index, row) {
      switch (index) {
        case 1:
          if (row.carNum != 0) {
            this.$router.push({
              // path: "management-slagTruck",
              path: "management-recordByCar",
              query: {
                projectId: row.projectId,
                statisticsTime: this.dateRange
              }
            });
          }
          break;
        case 2:
          if (row.sum != 0) {
            this.$router.push({
              path: "management-ledgerManagement",
              query: {
                projectId: row.projectId,
                statisticsTime: this.dateRange
              }
            });
          }
          break;
        case 3:
          if (row.normal != 0) {
            this.$router.push({
              path: "management-ledgerManagement",
              query: {
                projectId: row.projectId,
                statisticsTime: this.dateRange,
                status: 1
              }
            });
          }
          break;
        case 4:
          if (row.abnormal != 0) {
            this.$router.push({
              path: "management-ledgerManagement",
              query: {
                projectId: row.projectId,
                statisticsTime: this.dateRange,
                status: 0
              }
            });
          }
          break;
      }
    }
  },
  // 审核
  auditHandle(id, flag, row) {
    var ids = id
      ? [id]
      : this.dataListSelections.map(item => {
          return item.id;
        });
    this.auditVisible = true;
    this.$nextTick(() => {
      this.$refs.ledgerAudit.init(ids, flag, row);
    });
  },

  // 批量审核
  batchAudit() {}
};
</script>

<style>
.drilling {
  color: rgb(62, 142, 247);
  cursor: pointer;
}
.nomrol {
  color: #000;
}
</style>
